package nahuel.games.carracer;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import android.graphics.Bitmap;
import android.graphics.Canvas;

public class Esquina extends Calle {

	private int xInicial;
	private int xFinal;
	private int anchoD;
	private int altoD;
	private List<Trafico> autosCirculantes;
	private GameView vista;
	private Random rnd;
	private long timeTrafico = 0;
	
	private static final int PORC_CREACION = 15;
	private static final int DELAY_TRAFICO = 5000;

	public Esquina(Bitmap imagen, GameView vista, int xIni, int xFin, int anchoD, int altoD){
		super(imagen, xIni, xIni);
		this.xInicial = xIni;
		this.xFinal = xFin;
		this.anchoD = anchoD;
		this.altoD = altoD;
		this.vista = vista;
		this.autosCirculantes = new ArrayList<Trafico>();
		this.rnd = new Random();
	}
	
	@Override
	public boolean enRuta(int posX, int posY) {
		return (posX > xInicial && posX < xFinal);
	}

	@Override
	public void draw(Canvas canvas, int posx, int posy) {
		canvas.drawBitmap(imagen, posx, posy, null);
		Iterator<Trafico> it = autosCirculantes.iterator();
		while (it.hasNext()){
			Trafico trafico = it.next();
			trafico.draw(canvas, posy);
		}
	}

	public void update(int velRelativaY){
		Iterator<Trafico> it = autosCirculantes.iterator();
		while (it.hasNext()){
			Trafico trafico = it.next();
			trafico.update(velRelativaY);
		}
		agregarTrafico();		
	}
	
	private void agregarTrafico() {
		int prob = rnd.nextInt(100);
		if ((prob <= PORC_CREACION) && (timeTrafico + DELAY_TRAFICO < System.currentTimeMillis())) {
			autosCirculantes.add(new Trafico(vista, Trafico.HORIZONTAL, rnd.nextInt(2), anchoD, altoD));
			timeTrafico = System.currentTimeMillis();
		}
	}

}
